<?php

class FormAction_Index extends FormAction
{

  public $limit = 10;

  public $sortField;

  public $sortDirection;

  protected $action = Form::ACTION_INDEX;

  protected $pager;

  public function execute()
  {
    $this->loadData();
  }

  public function render()
  {
    $view = $this->getView();

    $view->set('pager', $this->pager);

    return parent::render();
  }

  protected function loadData()
  {
    $params = array();

    if (! empty($this->sortField)) {
      $params['orderBy'] = array($this->sortField, $this->sortDirection);
    }

    $fields = array($this->form->getPk());
    $where = array();
    $data = array();

    foreach ($this->form->getFilters() as $filter) {
      $key = $filter->getForeignKey();
      $val = $filter->getValue();

      $where[] = "$key = :$key";

      $data[$key] = $val;

      $fields[] = $key;
    }

    if (! empty($where)) {
      $params['where'] = array_merge((array) sy_get_param($params, 'where'), $where);
      $params['data'] = array_merge((array) sy_get_param($params, 'data'), $data);
    }

    $elements = $this->form->getElements($this->action);
    while ($element = $elements->next()) {
      $fields[] = $element->getField();
    }

    $params['fields'] = array_filter(array_unique($fields));
    $params['limit'] = $this->getLimit();
    $params['offset'] = $this->getOffset();

    $this->data = $this->gateway()->findAll($params);
    $this->pager = $this->gateway()->findPager($params);
  }

  protected function getOffset()
  {
    return Simplify::request()->get('offset');
  }

  protected function getLimit()
  {
    return $this->limit;
  }

}
